# -*-coding:utf-8-*-
import HTMLTestRunner
import time
import unittest
from config import globalconfig


class TestReport(object):

    def __init__(self, test_dir, case=None):
        self.test_dir = test_dir
        self.case = case

    def _suite(self):
        if not self.case:
            self.case = "alltestresult"
            pattern = "test*.py"
        else:
            pattern = "{}.py".format(self.case)
        suite = unittest.defaultTestLoader.discover(start_dir=self.test_dir, pattern=pattern)
        return suite

    def run(self):
        now = time.strftime('%Y-%m-%d_%H_%M_%S')
        suite = self._suite()
        reportname = globalconfig.report_path + "\\" + self.case + now + ".html"
        with open(reportname, 'wb') as f:
            runner = HTMLTestRunner.HTMLTestRunner(
                stream=f,
                title='测试报告',
                description='Test the import testcase'
            )
            runner.run(suite)
